<template>
  <a-modal title="地址管理" :width="660" :visible="visible" @ok="handleModalConfirm"
    @cancel="handleModalCancel" :confirm-loading="modalLoading" @after-open="saveFocusedElement" @after-close="restoreFocusedElement">
    <a-button class="editable-add-btn" @click="handleAdd" style="margin-bottom: 20px;">
      新增地址
    </a-button>
    <a-table :columns="columns" :data-source="addressList" >
      <a slot="name" slot-scope="text">{{ text }}</a>
      <span slot="address" slot-scope="text, record">
        <span>{{ record.province_name }}{{ record.city_name }}{{ record.district_name }}{{ record.address }}</span>
      </span>
      <div slot="id" slot-scope="text, record">
        <a-popconfirm
          title="确认要删除该地址?"
          @confirm="() => onDelete(record)"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
        <a style="margin-left: 18px;" @click="address_modify(record)">修改</a>
      </div>
      
    </a-table>
    <a-modal
      v-model="visibleAddress"
      :title="operationMode === 'add' ? '新增收货信息' : '修改地址'"
      @ok="handleOkAddress"
      @cancel="handleModalCancelAddress"
    >
      <a-form-model
        ref="form2"
        :model="form2"
        :rules="formRules2"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <!-- <a-form-model-item label="智能识别" prop="consignee">
          <a-textarea
            v-model="form.intelligent"
            placeholder="请输入"
            :auto-size="{ minRows: 3, maxRows: 3 }"
          />
          <a-button type="primary" @click="handleOkAddress">一键识别</a-button>
        </a-form-model-item> -->
        <a-form-model-item label="收货人" prop="consignee">
          <a-input v-model="form2.consignee" placeholder="请输入" allowClear />
        </a-form-model-item>
        <a-form-model-item label="手机号码" prop="mobile">
          <a-input v-model="form2.mobile" placeholder="请输入" allowClear  />
        </a-form-model-item>
        <a-form-model-item label="所在地区" prop="province_name">
          <area-select
            @change="selectArea"
            :default-value="form2.defaultArea"
          />
          
        </a-form-model-item>
        <a-form-model-item label="详细地址" prop="address">
          <a-textarea
            v-model="form2.address"
            placeholder="请输入"
            :auto-size="{ minRows: 3, maxRows: 3 }"
          />
        </a-form-model-item>
        <a-form-model-item label="默认地址">
          <a-switch v-model="form2.is_default" checked-children="开启" un-checked-children="关闭" style="margin-left: 10px;" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-modal>
</template>

<script>
import * as Ajax from '@/api/channel';
import { mapState, mapGetters } from "vuex";
import areaData from "../mission-hall/areaData";
import areaSelect from "../mission-hall/areaselect"
const columns = [
  {
    title: '收货人',
    dataIndex: 'consignee',
    key: 'consignee',
  },
  {
    title: '联系电话',
    dataIndex: 'mobile',
    key: 'mobile',
  },
  {
    title: '收货地址',
    dataIndex: 'address',
    scopedSlots: { customRender: 'address' },
  },
  {
    title: '操作',
    dataIndex: 'id',
    scopedSlots: { customRender: 'id' },
  },
];

const data = [
  
];

export default {
  props: {
    task_uuid: {
      type: String,
      default: '',
    },
    visible: {
      type: Boolean,
      default: false,
    },
   
    promotionId:{
      type: String,
      default: '',
    }
  },
  components: {
    areaSelect,
  },
  data() {
    return {
      modalLoading: false,
   
      tipShow:false,
      customersListOptions: [],
      nickname:'',
      data,
      columns,
      form2: {
        consignee: "",
        mobile: "",
        province_name: "",
        city_name: "",
        district_name: "",
        address: "",
        defaultArea: [],
        is_default: false,
        promotionId: null,
        institution_uuid: null,
      },
      formRules2: {
      // 其他规则
        consignee: [
          { required: true, message: '请输入收货人', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
        ],
        province_name: [
          { required: true, message: '请选择所在地区', trigger: 'change' },
        ],
        address: [
          { required: true, message: '请输入详细地址', trigger: 'blur' },
        ],
      },
      visibleAddress: false,
      areaData,
      addressList:[],
      addressID:'',
      operationMode: 'add',
    };
  },
  computed: {
    ...mapGetters("user", ["getCdnUrl", "getUserInfo"]),
  },
  methods: {
    processImage(imageUrl) {
      if (imageUrl === undefined || imageUrl === null) {
        return ""; // 或者返回一个默认的 URL
      }

      if (!imageUrl.startsWith("http")) {
        return this.getCdnUrl + imageUrl;
      }
      return imageUrl;
    },
    handleModalConfirm() {
      this.handleModalCancel()
    },
    
    handleModalCancel() {
      this.$emit('close');
    },
    saveFocusedElement() {
      this.focusedElement = document.activeElement;
    },
    restoreFocusedElement() {
      if (this.focusedElement) {
        this.focusedElement.focus();
      }
    },
    handleAdd(){
      this.operationMode = 'add';
      this.visibleAddress = true;
    },
    handleOkAddress() { 
      this.form2.promotionId = this.promotionId;
      this.$refs.form2.validate((valid) => {
        if (valid) {

          // 发送请求添加收货地址
          Ajax.add_address(this.form2).then((res) => {
            if (res.error === 0) {
              this.$message.success('收货地址添加成功');
              // 刷新收货地址列表
              this.get_addressList()
              this.handleModalCancelAddress()
            }
          });
        } else {
          console.log('表单校验失败');
        }
      });
    },
    handleModalCancelAddress() {
      this.visibleAddress = false;
      //清空表单数据
      this.form2 = {
        consignee: '',
        mobile: '',
        province_name: '',
        city_name: '',
        district_name: '',
        address: '',
        defaultArea: [],
        is_default: false,
        promotionId: null,
        institution_uuid: null,
      };
    },
    //选择地区之后的回调
    selectArea(selectedValues) {
      console.log("selectedValues", selectedValues);

      const [provinceId, cityId, districtId] = selectedValues;

      const province = this.areaData.find(prov => prov.code === provinceId);
      this.form2.province_name = province ? province.name : '';
      this.form2.province_id = provinceId;

      if (province) {
        const city = province.children?.find(city => city.code === cityId);
        this.form2.city_name = city ? city.name : '';
        this.form2.city_id = cityId;

        if (city) {
          const district = city.children?.find(district => district.code === districtId);
          this.form2.district_name = district ? district.name : '';
          this.form2.district_id = districtId;
        } else {
          this.form2.district_name = '';
          this.form2.district_id = '';
        }
      } else {
        this.form2.city_name = '';
        this.form2.district_name = '';
        this.form2.city_id = '';
        this.form2.district_id = '';
      }
      this.form2.region = this.form2.province_name +'-'+ this.form2.city_name +'-'+ this.form2.district_name;
      console.log("this.form2", this.form2);
    },
    get_addressList(){
      Ajax.addressList({promotionId:this.addressID,institution_uuid:this.getUserInfo.userLinkInstitution.institution_uuid}).then((res) => {
        if (res.error === 0) {
          this.addressList = res.data
        }
      })
    },
    onDelete(item){
      console.log(item.id);
      Ajax.addressDel(item.id).then((res) => {
          if (res.error === 0) {
            //删除成功
            this.$message.success('删除成功');
            this.get_addressList()
          }
        });
    },
    address_modify(item){
      console.log(item);
      this.operationMode = 'edit';
      this.visibleAddress = true;
      const arr = [item.province_id, item.city_id, item.district_id]
      const strArr = arr.map(num => num.toString());
      this.form2 = {
        consignee: item.consignee,
        mobile: item.mobile,
        province_name: item.province_name,
        city_name: item.city_name,
        district_name: item.district_name,
        address: item.address,
        defaultArea: strArr,
        is_default: item.is_default,
        promotionId: this.promotionId,
        institution_uuid: this.getUserInfo.userLinkInstitution.institution_uuid,
      };
      console.log('this.form2', this.form2);
      
    }
  },
  
  mounted() {
    
    this.form2.institution_uuid = this.getUserInfo.userLinkInstitution.institution_uuid;
    
  },
  watch: {
    promotionId(newVal) {
      this.addressID = newVal;
      this.get_addressList()
    }
  }
};
</script>

<style lang="scss" scoped>
.table-wrap {
  margin-top: 20px;
  padding-top: 16px;
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;
}

::v-deep .ant-form-item {
  &:last-child {
    margin-bottom: 0;
  }
}
.tips_box {
  padding: 4px;
}
.text{
  // font-size: 16px;
  color: #999999;
  margin: 10px 0;
  // text-align: center;
  span {
    color: #E33B35;
  }
}
.sale {
  display: flex;
  align-items: center;
  margin-left: 4px;
  margin-bottom: 10px;
  div {
    font-size: 14px;
    span {
      color: #E33B35;
    }
  }
}
</style>